package com.kintreda.tools.upload.minio;

import com.kintreda.common.config.exception.CommonBaseErrorCode;
import com.kintreda.common.config.exception.CommonBaseException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;

/**
 * 自建服务器上传
 */
@Component
public class MinioUtils {

    @Autowired
    private MinioService minioService;
    @Value("${upload.minio.bucketName}")
    private String bucketName;


    private static String[] fileSuffix = {"jpg", "bmp", "jpeg", "png", "gif","mp4","3gp","webm","flv","mkv","doc","docx","xls","xlsx","pdf","mp3","aac"};

    /**
     * 开始上传
     * @param file
     * @return
     */
    public String upload(MultipartFile file) {
        //判断图片是否为空
        if (file.isEmpty()) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_IS_EMPTY);
        }
        // 判断是否是合法的文件后缀
        int dotPos = file.getOriginalFilename().lastIndexOf(".");
        if (dotPos < 0) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_FORMAT_ERROR);
        }
        String fileExt = file.getOriginalFilename().substring(dotPos + 1).toLowerCase();
        boolean flag = false;
        for (String s : fileSuffix) {
            if (s.equals(fileExt)) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_FORMAT_ERROR);
        }
        //判断文件大小
        if (file.getSize() > 50 * 1024 * 1024) {
            throw new CommonBaseException(CommonBaseErrorCode.USER_PICTURE_OVERSIZE);
        }
        List<String> upload = minioService.upload(bucketName, new MultipartFile[]{file});
        return upload.get(0);
    }

}
